<script lang="ts" setup>
import * as echarts from 'echarts/core';
import {
  BarChart,
  LineChart
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  // 数据集组件
  DatasetComponent,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import type { ECOption } from '~/types'
import { ref, computed, unref, onMounted } from 'vue';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

const {options, width = '', height = '500px'} = defineProps<{
  options: ECOption;
  width?: string | number;
  height?: string | number;
}>()

const elRef = ref<HTMLElement>()

let echartRef: echarts.ECharts | null = null

const styles = computed(() => {
  const widthStr = typeof(width) === 'string' ? width : `${width}px`
  const heightStr = typeof(height) === 'string' ? height : `${height}px`

  return {
    width: widthStr,
    height: heightStr
  }
})

const initChart = () => {
  if (unref(elRef) && options) {
    echartRef = echarts.init(unref(elRef))
    echartRef?.setOption(options)
  }
}

onMounted(() => {
  console.log('init chart', styles.value)
  initChart()
})
</script>

<template>
  <div ref="elRef" :style="styles"></div>
</template>
